#!/usr/bin/env bash

prog="$1"
data="$(od -An -b -w6 $prog)"

function dec8() {
    printf "%d" "0$1"
}

function dec16() {
    printf "%x" "$1"
}

function decv16() {
    printf "%x" "0$1"
    [[ ! -z "$2" ]] && [[ "$2" != "000" ]] && printf "%x" "$2"
}

function decv10() {
    printf "%d" "$1"
    [[ ! -z "$2" ]] && [[ "$2" != "000" ]] && printf "%d" "$2"
}

function decop() {
    op="0x$(printf "%x" 0$1 | tr -t [:lower:] [:upper:])"
    txt="$(grep -e "$op$" vm.h | cut -d' ' -f2)"
    printf "(%2x) " "$op"
    if [[ "$txt" =~ J.*S  ]]; then
        printf "\e[1m\e[32m%4s\e[0m" "$txt"
    elif [[ "$txt" =~ "RST" ]]; then
        printf "\e[32m%4s\e[0m" "$txt"
    elif [[ "$txt" =~ J.* ]]; then
        printf "\e[1m\e[31m%4s\e[0m" "$txt"
    elif [[ "$txt" == "INIT" ]] || [[ "$txt" == "HALT" ]]; then
        printf "\e[1m\e[33m%4s\e[0m" "$txt"
    elif [[ "$txt" == "ADD" ]] || [[ "$txt" == "SUB" ]] ||
         [[ "$txt" == "MLT" ]] || [[ "$txt" == "DIV" ]] ||
         [[ "$txt" == "INC" ]] || [[ "$txt" == "DEC" ]] ||
         [[ "$txt" == "MOD" ]]; then       
        printf "\e[1m\e[37m%4s\e[0m" "$txt"
    elif [[ "$txt" == "AND" ]] || [[ "$txt" == "OR" ]] ||
         [[ "$txt" == "XOR" ]] || [[ "$txt" == "NOT" ]]; then
        printf "\e[1m\e[36m%4s\e[0m" "$txt"
    elif [[ "$txt" == "CRR" ]] || [[ "$txt" == "CRI" ]] ||
         [[ "$txt" == "CRM" ]]; then
        printf "\e[1m\e[35m%4s\e[0m" "$txt"
    else
        printf "%4s" "$txt"
    fi
}

i=0
while IFS=$' ' read -r -a line; do
    printf "[@%4s]|O:%s|R:%3s,%3s,%3s|V:0x%-2s (%s)\n" \
           "$(dec16 $i)" "$(decop ${line[0]})" "$(dec8 ${line[1]})" "$(dec8 ${line[2]})" \
           "$(dec8 ${line[3]})" "$(decv16 ${line[4]} ${line[5]})" "$(decv10 ${line[4]} ${line[5]})"
    ((i++))
done <<<"$data"



